package Servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;

import Bean.CheckBean;
import lookMessage.LookMessageBean;
import loginRegister.LoginBean;
import Bean.SqlBean;

/**
 * @author 黄忠
 * 创建于2019-06-01
 */

@WebServlet(urlPatterns = {"/upload"})
@MultipartConfig(location = "E:\\JavaProjects\\TXImages")// location为项目相对地址的绝对地址
public class UploadFileServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession(true);
        LoginBean login=(LoginBean) session.getAttribute("login");
        if(login!=null){
            Part part = request.getPart("picture");
            String fileName = part.getSubmittedFileName();
            System.out.println("上传文件的文件名: " + fileName);
            String [] nameSplit= fileName.split("\\.");
            if(nameSplit.length==0){
                response.getWriter().write("<script>alert('你再这样就封号了!');location.href='http://localhost:8080/infor.jsp'</script>");
                return;
            }
            String format = nameSplit[nameSplit.length-1];
            if(!(format.equalsIgnoreCase("jpg")||format.equalsIgnoreCase("png"))){
                response.getWriter().write("<script>alert('仅支持jpg和png格式图片!');location.href='http://localhost:8080/infor.jsp'</script>");
                return;
            }
            Date d = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String now = df.format(d);
            fileName = now+"."+nameSplit[nameSplit.length-1];
            String filePar = "E:\\JavaProjects\\TXImages\\"+login.getUserName();// 文件夹路径
            File myPath = new File(filePar);
            if (!myPath.exists()){//若此目录不存在，则创建之
                myPath.mkdir();
                System.out.println("创建文件夹路径为："+ filePar);
            }
            part.write(login.getUserName()+"\\"+fileName);
            try {
                ResultSet rs = null;
                SqlBean sb = new SqlBean();
                sb.connectSQL();
                String sql = "Update user set picture='" + fileName + "' where userName='" + login.getUserName() + "'";
                sb.executeUpdate(sql);
                String sql2 = "select * from user where userName='" + login.getUserName() + "'";
                rs = sb.executeQuery(sql2);
                LookMessageBean mm = new LookMessageBean();
                while (rs.next()) {
                    mm.setName(rs.getString("name"));
                    mm.setSex(rs.getString("sex"));
                    mm.setIdCard(rs.getString("idCard"));
                    mm.setBirth(rs.getString("birth"));
                    mm.setNation(rs.getString("nation"));
                    mm.setEdu(rs.getString("edu"));
                    mm.setWork(rs.getString("work"));
                    mm.setMonthPay(rs.getString("monthPay"));
                    mm.setPhone(rs.getString("phone"));
                    mm.setPlace(rs.getString("place"));
                    mm.setEmail(rs.getString("email"));
                    mm.setLevel(rs.getString("level"));
                    mm.setPicture(rs.getString("picture"));
                    mm.setDgut_username(rs.getString("dgut_username"));
                }
                session.setAttribute("wordlist", mm);
                sb.closeSQL();
                CheckBean.alert("头像修改成功！");
                response.sendRedirect("http://localhost:8080/lookMessage/lookMessage.jsp");
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        else response.sendRedirect("http://localhost:8080/lookMessage/lookMessage.jsp");

    }
}